/**
 * 网络监控器
 * 用于监控节点速度和选择最佳节点
 */
class NetworkMonitor {
  constructor() {
    this.peerStats = new Map();
    this.speedWindow = 10; // 统计最近10次的速度
    this.lastUpdateTime = Date.now();
    this.lastDownloadedSize = 0;
    this.speedHistory = [];
  }

  recordSuccess(peer, bytes) {
    if (!this.peerStats.has(peer)) {
      this.peerStats.set(peer, {
        totalBytes: 0,
        totalTime: 0,
        successCount: 0,
        failureCount: 0,
        avgSpeed: 0,
        lastSuccess: Date.now()
      });
    }

    const stats = this.peerStats.get(peer);
    const now = Date.now();
    const duration = now - (stats.lastSuccess || now);
    
    stats.totalBytes += bytes;
    stats.totalTime += duration;
    stats.successCount++;
    stats.lastSuccess = now;
    
    // 计算平均速度 (bytes/ms)
    if (stats.totalTime > 0) {
      stats.avgSpeed = stats.totalBytes / stats.totalTime;
    }
  }

  recordFailure(peer) {
    if (!this.peerStats.has(peer)) {
      this.peerStats.set(peer, {
        totalBytes: 0,
        totalTime: 0,
        successCount: 0,
        failureCount: 0,
        avgSpeed: 0,
        lastSuccess: Date.now()
      });
    }

    const stats = this.peerStats.get(peer);
    stats.failureCount++;
    
    // 失败后降低该节点的优先级
    stats.avgSpeed *= 0.5;
  }

  async selectBestPeer(peers) {
    if (peers.length === 0) {
      throw new Error('没有可用的节点');
    }

    if (peers.length === 1) {
      return peers[0];
    }

    // 计算每个节点的得分
    const scores = peers.map(peer => {
      const stats = this.peerStats.get(peer);
      
      if (!stats) {
        // 新节点，给予中等优先级
        return { peer, score: 0.5 };
      }

      // 综合考虑速度和成功率
      const successRate = stats.successCount / (stats.successCount + stats.failureCount);
      const speedScore = Math.min(stats.avgSpeed / 1000, 1); // 归一化速度
      const timeDecay = Math.exp(-(Date.now() - stats.lastSuccess) / 60000); // 时间衰减
      
      const score = successRate * 0.4 + speedScore * 0.4 + timeDecay * 0.2;
      
      return { peer, score };
    });

    // 使用加权随机选择，给高分节点更大概率
    const totalScore = scores.reduce((sum, { score }) => sum + score, 0);
    let random = Math.random() * totalScore;
    
    for (const { peer, score } of scores) {
      random -= score;
      if (random <= 0) {
        return peer;
      }
    }

    // 默认返回第一个
    return peers[0];
  }

  getAverageSpeed() {
    const now = Date.now();
    const timeDiff = (now - this.lastUpdateTime) / 1000; // 转换为秒
    
    if (timeDiff === 0) return 0;
    
    // 计算所有节点的总速度
    let totalSpeed = 0;
    let activeNodes = 0;
    
    for (const stats of this.peerStats.values()) {
      if (stats.avgSpeed > 0 && now - stats.lastSuccess < 10000) {
        totalSpeed += stats.avgSpeed * 1000; // 转换为 bytes/s
        activeNodes++;
      }
    }
    
    return activeNodes > 0 ? totalSpeed / activeNodes : 0;
  }

  getETA(remainingBytes) {
    const avgSpeed = this.getAverageSpeed();
    
    if (avgSpeed === 0) {
      return -1; // 未知
    }
    
    return Math.ceil(remainingBytes / avgSpeed); // 秒
  }

  reset() {
    this.peerStats.clear();
    this.speedHistory = [];
    this.lastUpdateTime = Date.now();
  }
}

module.exports = NetworkMonitor;

